﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using OpenSourceCompany0405.Models;

namespace OpenSourceCompany0405.Controllers;

[Authorize] // 必须登录才能访问
public class ProfileController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    // GET: 显示个人信息编辑页面
    [HttpGet]
    public async Task<IActionResult> Index()
    {
        var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound();
        }

        var model = new ProfileViewModel
        {
            Email = user.Email,
            EquityCoin = user.EquityCoin,
            ThisMonthHaveValue = user.ThisMonthHaveValue,
            HaveInitLevel = user.HaveInitLevel,
            StrategyLevel = user.StrategyLevel,
            TacticianLevel = user.TacticianLevel,
            WarriorLevel = user.WarriorLevel,
            FullName = user.FullName,
            Gender = user.Gender
        };

        if (user.EquityCoin == null)
        {
            model.EquityCoin = 0;
        }
        if (user.StrategyLevel == null)
        {
            model.StrategyLevel = 0;
        }
        if (user.TacticianLevel == null)
        {
            model.TacticianLevel = 0;
        }
        if (user.WarriorLevel == null)
        {
            model.WarriorLevel = 0;
        }
        
        return View(model);
    }

    // POST: 处理表单提交
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(ProfileViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // 输出所有验证错误到控制台
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            foreach (var error in errors)
            {
                Console.WriteLine($"Error: {error.ErrorMessage}");
            }
            return View(model);
        }

        var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound();
        }
        if (user != null)
        {
            model.Email = user.Email; // 覆盖客户端可能提交的空值
        }
        // 更新用户信息
        user.FullName = model.FullName;
        user.Gender = model.Gender;

        var result = await _userManager.UpdateAsync(user);
        if (result.Succeeded)
        {
            TempData["SuccessMessage"] = "个人信息已更新";
            return RedirectToAction(nameof(Index));
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }

        return View(model);
    }
}